package com.tilaiedu.mvc.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @Author xlzhang
 * @Date 2022/5/25 14:12
 * @Version 1.0
 * @Description TODO
 */
@Configuration
@MapperScan("com.tilaiedu.mvc.mapper")
@PropertySource("classpath:jdbc.properties")
public class MybatisConfig {
    // 注入配置文件的数据
    @Value("${mysql.url}")
    private String url;
    @Value("${mysql.driverName}")
    private String driverName;
    @Value("${mysql.user}")
    private String username;
    @Value("${mysql.password}")
    private String password;


    @Bean("dataSource")
    public DataSource getDataSource(){
        final DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        // 设置数据源
        factoryBean.setDataSource(dataSource);
        // 设置javabean的别名,默认是将类名称首字母小写
        factoryBean.setTypeAliasesPackage("com.tilaiedu.mvc.entity");
        factoryBean.setTypeAliasesPackage("com.tilaiedu.mvc.vo");
        // 设置分页插件
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties prop = new Properties();
        prop.setProperty("helperDialect", "mysql");
        pageInterceptor.setProperties(prop);
        factoryBean.setPlugins(pageInterceptor);

        return factoryBean.getObject();
    }

}
